package commands

import (
	"fmt"
	"github.com/bytedance/sonic"
	"github.com/duke-git/lancet/v2/fileutil"
	"github.com/goravel/framework/contracts/console"
	"github.com/goravel/framework/contracts/console/command"
	"github.com/goravel/framework/contracts/queue"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/color"
	json2 "github.com/goravel/framework/support/json"
	"github.com/xuri/excelize/v2"
	"goravel/app/jobs"
	"goravel/app/models"
	"gorm.io/datatypes"
	"strconv"
	"strings"
	"time"
)

type Demo01 struct {
}

// Signature The name and signature of the console command.
func (receiver *Demo01) Signature() string {
	return "cmd:demo01"
}

// Description The console command description.
func (receiver *Demo01) Description() string {
	return "Command description"
}

// Extend The console command extend.
func (receiver *Demo01) Extend() command.Extend {
	return command.Extend{}
}

// Handle Execute the console command.
func (receiver *Demo01) Handle(ctx console.Context) error {
	return nil
}

func (receiver *Demo01) jobTest() error {
	err := facades.Queue().Job(&jobs.DemoJob{}, []queue.Arg{}).Dispatch()
	return err
}

func (receiver *Demo01) excelTest() {
	f, err := excelize.OpenFile("C:\\Users\\thoom\\Desktop\\广西移动B站短视频在线.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	source := "bilibili"
	rows, err := f.GetRows("在线片单")
	if err != nil {
		fmt.Println(err)
		return
	}
	for index, row := range rows {
		if index == 0 {
			continue
		}
		if index > 1000 {
			break
		}
		fmt.Println(index, "\t id:", row[0], "\t name:", row[1])
		sourceId := row[0]
		tags := strings.Split(row[7], "|")
		tagsStr, err := json2.MarshalString(tags)
		if err != nil {
			tagsStr = ""
		}
		isVertical, err := strconv.Atoi(row[8])
		if err != nil {
			isVertical = 0
		}
		incomingTime, err := time.Parse("2006-01-02 15:04:05", row[9])
		if err != nil {
			incomingTime = time.Now()
		}
		showTime, err := time.Parse("2006-01-02 15:04:05", row[10])
		if err != nil {
			showTime = time.Now()
		}

		dao := models.ShortVideo{
			Source:          source,
			SourceId:        sourceId,
			Title:           row[1],
			Author:          row[2],
			Remark:          row[3],
			Tags:            datatypes.JSON(tagsStr),
			Status:          1,
			IsVertical:      isVertical,
			IncomingTime:    incomingTime,
			ShowTime:        showTime,
			CopyrightExpiry: time.Now().Add(10 * 365 * 24 * time.Hour),
		}
		err = facades.Orm().Query().Create(&dao)
		if err != nil {
			// fmt.Println(err.Error())
			color.New(color.FgRed).Println(err.Error())
		}
	}
}

func (receiver *Demo01) dirTest() {
	names, err := fileutil.ListFileNames("D:\\B")
	if err != nil {
		fmt.Println(err)
	}
	for _, name := range names {
		if strings.Contains(name, ".mp3") {
			fmt.Println(name)
		}
		//if str.Of(name).EndsWith(".mp4") {
		//	fmt.Println(name)
		//}
	}
}

func (receiver *Demo01) jsonTest() {
	o1 := map[string]any{
		"name":  "superwen",
		"email": "thoomi@qq.com",
		"age":   32,
	}
	jsonByte, err := sonic.Marshal(o1)
	if err != nil {
		fmt.Println("err is:", err)
	}
	fmt.Println(string(jsonByte))
}

// cacheTest 测试缓存
func (receiver *Demo01) cacheTest() {
	key := "name"
	if facades.Cache().Has(key) {
		value := facades.Cache().GetString(key)
		fmt.Println("cache is:", value)
	} else {
		now := time.Now().Format("2006-01-02 15:04:05")
		fmt.Println("now is:", now)
		_ = facades.Cache().Put(key, now, 10*time.Minute)
	}
}

// fileTest 测试文件
func (receiver *Demo01) fileTest() {
	filePath := "project/demo/example.txt"
	if !facades.Storage().Exists(filePath) {
		err := facades.Storage().Put(filePath, "Contents")
		if err != nil {
			fmt.Println("err is:", err)
		}
	} else {
		fmt.Println("file exists")
	}

	// 输出CDN路径
	fmt.Println(facades.Storage().Url(filePath))
	// 输出临时路径（有效期）
	fmt.Println(facades.Storage().TemporaryUrl(filePath, time.Now().Add(5*time.Minute)))

	err := facades.Queue().Job(&jobs.DemoJob{}, []queue.Arg{}).Dispatch()
	if err != nil {
		fmt.Println("err is:", err)
	}
}
